<template>
	<!-- 1. 表单组件: uni-forms=> 背后是一个.vue 格式的文件 -->
	<uni-forms :model="formData" :rules="rules" validateTrigger="blur" class="login-form" ref="accountForm">
		<!--  账号 
		 注意：name 的值要和formData中的属性名一致，将来校验使用
		-->
		<uni-forms-item name="account">
			<!-- 			<input type="text" v-model="formData.account" placeholder="请输入账号" class="uni-input-input"
				placeholder-style="color: #818181" /> -->
			<!--  说明：使用uni-easyinput组件可以出发 blur 校验 -->
			<uni-easyinput v-model="formData.account" placeholder="请输入账号" />
		</uni-forms-item>
		<!-- 密码 -->
		<uni-forms-item name="password">
			<!-- 			<input type="text" v-model="formData.password" placeholder="请输入密码" class="uni-input-input"
				placeholder-style="color: #818181" /> -->
			<uni-easyinput v-model="formData.password" placeholder="请输入密码" />
		</uni-forms-item>
		<button @click="onFormSubmit" class="submit-button">登录</button>
	</uni-forms>
</template>

<script setup>
	import { ref } from 'vue'
	import { loginApi } from '@/apis/user'
	import { onLoad } from '@dcloudio/uni-app'
	import { useUserStore } from '@/stores/user.js'
	const store = useUserStore()
	// 1.  表单数据
	const formData = ref({
		account: 'maoyec',
		password: '123456'
	})
	// 2.  表单校验规则 rules
	const rules = {
		account: {
			rules: [
				{ required: true, errorMessage: '请输入登录账号' },
				{ pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
			],
		},
		password: {
			rules: [
				{ required: true, errorMessage: '请输入登录密码' },
				{ pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
			],
		},
	}
	// 3. 兜底校验
	// 回跳地址
	const redirectURL = ref('')
	// 跳转地址方式
	const routeType = ref('')

	// 获取地址中的参数
	onLoad((query) => {
		console.log(' 回跳地址：', query.redirectURL)
		redirectURL.value = decodeURIComponent(query.redirectURL)
		routeType.value = query.routeType
	})
	// 1. 定义 ref 变量用来获取表单组件的实例
	const accountForm = ref()
	const onFormSubmit = async () => {
		try {
			// 验证通过
			// 2.  获取表单组件实例 =》accountForm.value （vue3）|| this.$refs.accountForm(vue2)，用于兜底校验
			console.log('表单组件实例：', accountForm.value);
			const formData = await accountForm.value.validate()
			// 表单的数据
			console.log('成功：', formData)
			// 调用登录接口
			const res = await loginApi(formData)
			// 记录用户登录成功后的状态
			store.setToken(res.data)
			//  跳转之前访问的401页面
			if (routeType.value === 'switchTab') {
				uni.switchTab({ url: redirectURL.value })
			} else {
				uni.redirectTo({
					url: redirectURL.value
				})
			}
		} catch (err) {
			// 验证失败
			console.log('失败：', err)
		}
	}
</script>

<style lang="scss">
	@import './styles.scss';

	// 说明：https://github.com/dcloudio/uni-app/issues/1732
	//  如果覆盖 uni-ui 组件样式不生效，在样式前边加=》::v-deep
	::v-deep .uni-easyinput__content {
		border: 0;
	}

	::v-deep .uni-easyinput__content-input {
		font-size: $uni-font-size-base;
		padding-left: 0 !important;
	}
</style>